
<form id="form_devis" method="post" {{ form_enctype(form) }}>
    <div class="span12">
        <div class="box gradient">
            <div class="title">
                <h4 style="text-align: center">
                    DEVIS
                </h4>
            </div>

            <div class="content noPad clearfix">
                <table style="width: 100%">
                    <tr>
                        <td style="width: 20%">
                            <label>Date:</label>
                            <div>
                                    {{ form_widget(form.date)}}{{ form_widget(form._token)}}
                                    <input id="now" type="text" style="width: 70px;" readonly/>
                                    <img src="/images/start.jpg" height="30" width="30" style="display: none;" id="start"> 
                                    <img src="/images/previous.jpg" height="30" width="30" style="display: none;" id="prev"> 
                                </div>
                            </td>
                            <td  style="width: 20%">
                                <label>Client:</label><input type="hidden" id="gds_ventebundle_devistype_client" name="gds_ventebundle_devistype[client]" />
                                <div id="div_client" class="span8 controls" style="width: 200px">
                                    <div id='client'>
                                    </div>
                                    <script>
                                        var url = '{{path('gds_list_client_select')}}';
                                        var source =
                                                {
                                                    datatype: "json",
                                                    datafields: [
                                                        {name: 'id'},
                                                        {name: 'raison_social'}
                                                    ],
                                                    url: url,
                                                    async: false
                                                };
                                        var dataAdapter = new $.jqx.dataAdapter(source);
                                        $("#client").jqxComboBox({selectedIndex: -1, source: dataAdapter, displayMember: "raison_social", valueMember: "id", width: 200, height: 25});
                                        $("#client").on('select', function(event) {
                                            if (event.args) {
                                                var item = event.args.item;
                                                if (item) {
                                                    client_id = item.value
                                                    $('#gds_ventebundle_devistype_client').val(client_id)
                                                    var valueelement = $("<div></div>");
                                                    valueelement.text("Value: " + item.value);
                                                    var labelelement = $("<div></div>");
                                                    labelelement.text("Label: " + item.label);
                                                    $("#selectionlog").children().remove();
                                                    $("#selectionlog").append(labelelement);
                                                    $("#selectionlog").append(valueelement);
                                                } else {
                                                    client_id = 0
                                                }
                                            }
                                        });
                                        {% if (devis is defined ) %}
                                        client_id = {{devis.client.id}}
                                        client_old = client_id
                                        $("#client").jqxComboBox('val', '{{devis.client}}');
                                        {% else %}
                                        client_id = 1
                                        client_old = 1
                                            {% endif %}

                                        $('#gds_ventebundle_devistype_client').val(client_id)
                                        $('.jqx-widget-content').blur(function() {
                                            if (client_id == 0) {
                                                ajouterClient()
                                            } else
                                            if (client_old != client_id)
                                            {
                                                changerClient()
                                                client_old = client_id
                                            }
                                        })
                                        function ajouterClient() {
                                            raison_social_new = $('#client').val()
                                            $.msgBox({
                                                title: "Nouveau Client: " + raison_social_new,
                                                content: "M.F : <input id='mf'/> </br>Adresse : <input id='adresse'/> </br>GSM : <input id='gsm'/>",
                                                type: "confirm",
                                                buttons: [
                                                    {type: "submit", value: "Valider"},
                                                    {type: "cancel", value: "Annuler"}
                                                ],
                                                afterShow: function() {
                                                    $('#mf').focus()
                                                },
                                                success: function(result) {
                                                    if (result == "Valider") {
                                                        $.ajax({
                                                            url: "{{ path('gds_client_new_for_bl') }}",
                                                            data: 'raison_social=' + raison_social_new + '&matricule=' + $('#mf').val() + '&adresse=' + $('#adresse').val() + '&gsm=' + $('#gsm').val(),
                                                            success: function(data) {
                                                                if (data.success) {
                                                                    client_id = data.id
                                                                    client_old = client_id
                                                                    $('#gds_ventebundle_devistype_client').val(client_id)
                                                                    changerClient()
                                                                }
                                                            }
                                                        })
                                                    } else {
                                                        $('#client').focus()
                                                    }
                                                }
                                            });
                                        }
                                        </script>
                                    </div> 
                                </td>
                                <td  style="width: 20%">
                                    <label>Departement:</label>
                                    <div style="width: 200px">
                                    {{ render(controller('GdsVenteBundle:Devis:getAllDepartement')) }}
                                        </div> 
                                    </td>
                                    <td style="width: 20%">
                                        <label>Facturable:</label>
                                        <input id="facturable" type="checkbox">
                                    </td>
                                    <td  style="width: 40%">
                                        <label>Numero Devis:</label>
                                {{ form_widget(form.reference,{'attr':{'class':'span8 text','readonly':'readonly','style':'width:200px'}})}}
                                    </td>
                                </tr>
                            </table>

                        </div> 
                    </div>
                </div>
            </form>

            <div class="span12" style="margin-left:0">
                <table>
                    <tr>
                        <td id="td_familles">
                            <input type="text" id="familles" style="width:100%"/>
                        </td>
                        <td id="td_sous_familles">
                            <input type="text" id="sous_familles" style="width:100%"/>
                        </td>
                        <td id="td_articles">
                            <input type="text" id="articles" style="width:100%"/>
                        </td>
                    </tr>
                </table>
                <div class="box gradient">
                    <div class="content noPad clearfix">
                        <table id="table_devis" cellpadding="0" cellspacing="0" border="0" class="responsive  display table table-bordered" width="100%">
                            <thead>
                                <tr >
                                    <th style="text-align: center">N°</th>
                                    <th>Reference</th>
                                    <th>Designation</th>
                                    <th>Qte</th>
                                    <th id="th_dispo" style="width:5%">Dispo</th>
                                    <th>P.U.HT</th>
                                    <th>TVA</th>
                                    <th>Remise</th>
                                    <th>P.U.TTC</th>
                                    <th id="th_total" style="width:10%">Total</th>
                                    <th id="ok"></th>
                                </tr>
                            </thead>
                            <tbody id="gds_ventebundle_lignedevistype">
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="span2" style="margin-left:83%">
                    <div class="content noPad clearfix">
                        <table cellpadding="0" cellspacing="0" border="1px" class="responsive  display table table-bordered" width="100%" style="border:#D0E9F5 ">
                            <thead>
                                <tr >
                                    <th class="center" style="text-align: center">TOTAL TTC</th>
                                    <th id="total_ttc" class="center">0.000</th>

                                    <th class="center" style="text-align: center">Remise</th>
                                    <th id="total_remise" class="center">0.000</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>
    {# Ajout d'un lien pour ajouter un champ cat�gorie suppl�mentaire. #}
            <div class="span2" style="margin-left:0">
                <div class="box gradient">
                    <div class="content noPad clearfix">
                        <table id="taxe" cellpadding="0" cellspacing="0" border="0" class="responsive  display table table-bordered" width="100%">
                            <thead>
                                <tr>
                                    <th>Taxe</th>
                                    <th>Base</th>
                                    <th>Montant</th>
                                </tr>
                            </thead>
                            <tbody id="taxe_body">
                                <tr id="tr_taxe_18">
                                    <td id="taxe_18">18%</td>
                                    <td id="base_18">0.000</td>
                                    <td id="montant_taxe_18">0.000</td>
                                </tr>
                                <tr>
                                    <td>Totaux</td>
                                    <td></td>
                                    <td id="total_taxe">0.000</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="span2" style="margin-right: 0">
                <table>
                    <tr>
                        <td style="text-align: center">
                            <input type="button" style="width:100px" id="submit_form_devis" value="Enregistrer" class="nostyle btn btn-success btn-large" />
                        </td>
                        <td style="text-align: center">
                            <input type="button" style="width:100px" id="submit_form_devis_print" value="Imprimer" class="nostyle btn btn-success btn-large" />
                        </td>
                    </tr>
                    <tr>
                        <td style="height: 20px"></td>
                    </tr>
                    <tr>
                        <td>
                            <input id="retour2" style="width:100px" type="button" class="btn btn-info cut-icon-previous"  value="Retour" onclick="retourListeDevis2()">
                        </td>
                    </tr>
                </table>
            </div>

            <script>
                $(document).ready(function() {
                    $('#td_articles').hide()
                    $('#td_familles').hide()
                    $('#td_sous_familles').hide()
                    key_success = ''
                    key = '';
                    $('#now').keypress(function(event) {
                        key = key + String.fromCharCode(event.charCode);
                        if (event.charCode == 0) {
                            keyEnterPressed2()
                        }
                    });
                    $('#departement').change(function() {
                        if (key_success != '') {
                            key = key_success
                            keyEnterPressed2()
                        } else {
                            setTousQuantite();
                        }

                    })
                    $('#facturable').change(function() {
                        if (key_success != '') {
                            key = key_success
                            keyEnterPressed2()
                        }
                    })
                    $.ajax({
                        url: '{{path('gds_vente_get_all_articles')}}',
                        datatype: 'json',
                        data: 'client_id=' + client_id,
                        success: function(data) {
                            $("#articles").tokenInput(data, {
                                preventDuplicates: true,
                                onAdd: function(item) {
                                    $('.token-input-token').hide()
                                    var article = getArticle(item.id)
                                    if (!article) {
                                        add_ligne()
                                        var article = item.name.split(' : ');
                                        var reference = article[0]
                                        var designation = article[1]
                                        articles.push(item)
                                        var id = index - 1
                                        $('#td_reference_' + id).html(reference)
                                        $('#td_designation_' + id).html(designation)
                                        $('#gds_ventebundle_devistype_lignesDevis_' + id + '_article').val(item.id)
                                        remplir_ligne(id, item)
                                        setQuantite(id)
                                        var remise_max = item.remise_max;
                                        $('#gds_ventebundle_devistype_lignesDevis_' + id + '_taux_remise').spinner({
                                            min: 0,
                                            max: remise_max,
                                            step: 1,
                                            places: 2,
                                            showOn: 'both'
                                        });
                                    } else {
                                        id = article.index
                                    }
                                    $('#gds_ventebundle_devistype_lignesDevis_' + id + '_quantite').focus()
                                },
                            });
                            $('#td_articles').show()
                            $('#td_familles').show()
                            $('#td_sous_familles').show()
                        }
                    })
                    familles = []
                    sous_familles = []
                    $.ajax({
                        url: '{{path('gds_vente_get_all_familles')}}',
                        datatype: 'json',
                        success: function(data) {
                            $('#familles').tokenInput(data, {
                                preventDuplicates: true,
                                onAdd: function(item) {
                                    familles[familles.length] = item.id
                                    chercherSousFamilles()
                                    chercherArticles('famille')
                                },
                                onDelete: function(item) {
                                    familles.splice($.inArray(item.id, familles), 1);
                                    chercherSousFamilles()
                                    chercherArticles('famille')
                                },
                            });
                        }
                    })
                    $('#sous_familles').tokenInput('', {
                        preventDuplicates: true
                    });
                })
                function add_ligne() {
                    var td_num = '<td class="numero_ligne" style="padding:0;text-align:center" id="td_num_' + index + '">' + nb_article + '</td>';
                    var hidden_stock = '<input type="hidden" value="18" id="gds_ventebundle_devistype_lignesDevis_' + index + '_taux_tva" name="gds_ventebundle_devistype[lignesDevis][' + index + '][taux_tva]"/><input id="gds_ventebundle_devistype_lignesDevis_' + index + '_article" type="hidden" name="gds_ventebundle_devistype[lignesDevis][' + index + '][article]"/>';
                    var td_reference = '<td style="padding:0;width:10%" id="td_reference_' + index + '"></td>';
                    var td_designation = '<td style="padding:0;width:20%" id="td_designation_' + index + '"></td>';
                    var td_qte = '<td style="padding:0" id="td_qte_' + index + '"><input  class="quantite" style="padding:2%;width:60%" type="text" id="gds_ventebundle_devistype_lignesDevis_' + index + '_quantite" type="text"  name="gds_ventebundle_devistype[lignesDevis][' + index + '][quantite]" value="1" onkeyup="Test(this)"></td>';
                    var td_qte_dispo = '<td style="padding:0" id="td_qte_dispo_' + index + '"></td>';
                    var td_prix_unitaire_ht = '<td style="padding:0" id="td_prix_unitaire_ht_' + index + '"><input class="prix_unitaire_ht" style="padding:2%;width:95%" type="text" id="gds_ventebundle_devistype_lignesDevis_' + index + '_prix_unitaire_ht" type="text"  name="gds_ventebundle_devistype[lignesDevis][' + index + '][prix_unitaire_ht]" onkeyup="Test(this)"></td>';
                    var td_tva = '<td style="padding:0" id="td_tva_' + index + '">18.00%</td>';
                    var td_remise = '<td style="padding:0" id="td_remise_' + index + '"><input class="remise" style="padding:2%;width:60%" type="text" id="gds_ventebundle_devistype_lignesDevis_' + index + '_taux_remise" type="text"  name="gds_ventebundle_devistype[lignesDevis][' + index + '][taux_remise]" value="0" onkeyup="Test(this)"></td>';
                    var td_prix_u_ttc = '<td style="padding:0" id="td_prix_u_ttc_' + index + '"><input class="prix_u_ttc" style="padding:2%;width:95%" type="text" id="prix_u_ttc_' + index + '" type="text" onkeyup="Test(this)"></td>';
                    var td_total = '<td style="padding:0;width:10%" id="td_total_' + index + '">0.000</td>';
                    var td_delete = '<td style="padding:0" ><img src="/images/icons/delete.png" id="delete_ligne_' + index + '" onclick="delete_ligne(' + index + ')"></td>'
                    var tr_contenu = td_num + td_reference + td_designation + hidden_stock + td_qte + td_qte_dispo + td_prix_unitaire_ht + td_tva + td_remise + td_prix_u_ttc + td_total + td_delete;
                    var tr = $('<tr id="tr_' + index + '">' + tr_contenu + '</tr>')
                    $container.append(tr);
                    index++
                    nb_article++
                    b = tr.attr('id')
                    b = b.split('_')
                    b = b[1]
                    $('#gds_ventebundle_devistype_lignesDevis_' + b + '_quantite').spinner({
                        min: 0,
                        max: 10000,
                        step: 1,
                        places: 2,
                        showOn: 'both'
                    });
                    $('#gds_ventebundle_devistype_lignesDevis_' + b + '_quantite').keyup(function() {
                        var i = $(this).attr('id');
                        i = i.split('_');
                        i = i[4];
                        var quantite = $(this).val();
                        var article = getArticle($('#gds_ventebundle_devistype_lignesDevis_' + i + '_article').val())
                        article.quantite = quantite
                        var prix_vente_ht = article.prix_vente;
                        var tva = article.taux_tva;
                        var remise = article.remise;
                        var puttc = prix_vente_ht
                        puttc *= (1 + tva / 100)
                        puttc *= (1 - remise / 100)
                        puttc = puttc.toFixed(3)
                        $('#prix_u_ttc_' + i).val(puttc);
                        var total = puttc * quantite
                        $('#td_total_' + i).html(total.toFixed(3));
                        RefraichirTaxe()
                    });
                    $('#gds_ventebundle_devistype_lignesDevis_' + b + '_quantite').change(function() {
                        $(this).keyup()
                    });
                    $('#gds_ventebundle_devistype_lignesDevis_' + b + '_quantite').live('keypress', function(e) {
                        if (e.keyCode === 9) {
                            e.preventDefault();
                            var i = $(this).attr('id');
                            i = i.split('_');
                            i = i[4];
                            $('#gds_ventebundle_devistype_lignesDevis_' + i + '_taux_remise').focus()
                        }
                    });


                    $('#gds_ventebundle_devistype_lignesDevis_' + b + '_prix_unitaire_ht').keyup(function() {
                        var i = $(this).attr('id');
                        i = i.split('_');
                        i = i[4];
                        var prix_vente_ht = $(this).val();
                        var article = getArticle($('#gds_ventebundle_devistype_lignesDevis_' + i + '_article').val())
                        var quantite = article.quantite
                        var tva = article.taux_tva;
                        var remise = article.remise;
                        var puttc = prix_vente_ht
                        puttc *= (1 + tva / 100)
                        puttc *= (1 - remise / 100)
                        puttc = puttc.toFixed(3)
                        article.prix_vente = prix_vente_ht
                        $('#prix_u_ttc_' + i).val(puttc);
                        var total = puttc * quantite
                        $('#td_total_' + i).html(total.toFixed(3));
                        RefraichirTaxe()
                    });
                    $('#gds_ventebundle_devistype_lignesDevis_' + b + '_prix_unitaire_ht').change(function() {
                        var i = $(this).attr('id');
                        i = i.split('_');
                        i = i[4];
                        var prix_vente_ht = $(this).val();
                        var article = getArticle($('#gds_ventebundle_devistype_lignesDevis_' + i + '_article').val())
                        var quantite = article.quantite
                        var tva = article.taux_tva;
                        var remise = article.remise;
                        var puttc = prix_vente_ht
                        puttc *= (1 + tva / 100)
                        puttc *= (1 - remise / 100)
                        puttc = puttc.toFixed(3)
                        if (puttc < article.prix_vente_min_ttc) {
                            puttc = article.prix_vente_min_ttc
                            prix_vente_ht = puttc / ((1 + tva / 100) * (1 - remise / 100))
                            $(this).val(prix_vente_ht.toFixed(3))
                        }
                        var x = article.prix_vente_min_ttc / (prix_vente_ht * (1 + tva / 100))
                        var remise_max = (1 - x) * 100
                        article.remise_max = remise_max
                        $('#gds_ventebundle_devistype_lignesDevis_' + i + '_taux_remise').spinner({
                            min: 0,
                            max: remise_max,
                            step: 1,
                            places: 2,
                            showOn: 'both'
                        })
                        var prix_vente_min_ttc = prix_vente_ht * (1 + tva / 100) * (1 - remise_max / 100)
                        prix_vente_min_ttc = prix_vente_min_ttc.toFixed(3)
                        article.prix_vente_min_ttc = prix_vente_min_ttc
                        article.prix_vente = prix_vente_ht
                        $('#prix_u_ttc_' + i).val(puttc.toFixed(3));
                        var total = puttc * quantite
                        $('#td_total_' + i).html(total.toFixed(3));
                        RefraichirTaxe()
                    })

                    $('#gds_ventebundle_devistype_lignesDevis_' + b + '_taux_remise').spinner({
                        min: 0,
                        max: 100,
                        step: 1,
                        places: 2,
                        showOn: 'both'
                    });
                    $('#gds_ventebundle_devistype_lignesDevis_' + b + '_taux_remise').keyup(function() {
                        var i = $(this).attr('id');
                        i = i.split('_');
                        i = i[4];
                        doRemiseChange(i)
                        RefraichirTaxe()
                    });
                    $('#gds_ventebundle_devistype_lignesDevis_' + b + '_taux_remise').change(function() {
                        var i = $(this).attr('id');
                        i = i.split('_');
                        i = i[4];
                        doRemiseChange(i)
                        RefraichirTaxe()
                    });
                    $('#gds_ventebundle_devistype_lignesDevis_' + b + '_taux_remise').live('keypress', function(e) {
                        if (e.keyCode === 9) {
                            e.preventDefault();
                            var i = $(this).attr('id');
                            i = i.split('_');
                            i = i[4];
                            i++
                            if (i >= index && !$('.msgBoxTitle').html())
                                $('#articles').focus()
                            else {
                                while (i < index && $('#tr_' + i).html() == null) {
                                    i++
                                }
                                if ($('#tr_' + i).html() == null)
                                    $('#articles').focus()
                                else
                                    $('#gds_ventebundle_devistype_lignesDevis_' + i + '_quantite').focus()
                            }
                        }
                    });

                    $('#prix_u_ttc_' + b).keyup(function() {
                        var i = $(this).attr('id');
                        i = i.split('_');
                        i = i[3];
                        var puttc = $(this).val();
                        var article = getArticle($('#gds_ventebundle_devistype_lignesDevis_' + i + '_article').val())
                        var prix_vente_ht = article.prix_vente;
                        var quantite = article.quantite;
                        var tva = article.taux_tva;
                        var prix_sans_remise_ttc = prix_vente_ht * (1 + tva / 100)
                        prix_sans_remise_ttc = prix_sans_remise_ttc.toFixed(3)
                        var remise = 100;
                        if (prix_sans_remise_ttc != 0) {
                            remise = (1 - puttc / prix_sans_remise_ttc) * 100
                            remise = remise.toFixed(2)
                        }
                        article.remise = remise
                        $('#gds_ventebundle_devistype_lignesDevis_' + i + '_taux_remise').val(remise);
                        var total = puttc * quantite
                        $('#td_total_' + i).html(total.toFixed(3));
                        RefraichirTaxe()
                    });
                    $('#prix_u_ttc_' + b).change(function() {
                        var i = $(this).attr('id');
                        i = i.split('_');
                        i = i[3];
                        var puttc = $(this).val();
                        var article = getArticle($('#gds_ventebundle_devistype_lignesDevis_' + i + '_article').val())
                        if (puttc < article.prix_vente_min_ttc) {
                            puttc = article.prix_vente_min_ttc
                            $(this).val(puttc)
                        }
                        var prix_vente_ht = article.prix_vente;
                        var quantite = article.quantite;
                        var tva = article.taux_tva;
                        var prix_sans_remise_ttc = prix_vente_ht * (1 + tva / 100)
                        prix_sans_remise_ttc = prix_sans_remise_ttc.toFixed(3)
                        var remise = 100;
                        if (prix_sans_remise_ttc != 0) {
                            remise = (1 - puttc / prix_sans_remise_ttc) * 100
                            remise = remise.toFixed(2)
                        }
                        article.remise = remise
                        $('#gds_ventebundle_devistype_lignesDevis_' + i + '_taux_remise').val(remise);
                        var total = puttc * quantite
                        $('#td_total_' + i).html(total.toFixed(3));
                        RefraichirTaxe()
                    });
                    $('#gds_ventebundle_devistype_lignesDevis_' + b + '_taux_remise').dblclick(function() {
                        var i = $(this).attr('id');
                        i = i.split('_');
                        i = i[4];
                        var article = getArticle($('#gds_ventebundle_devistype_lignesDevis_' + i + '_article').val())
                        $.msgBox({
                            title: "Dépassement du remise",
                            content: "mdp: <input id='mdp' type='password' />",
                            type: "confirm",
                            buttons: [
                                {type: "submit", value: "Valider"},
                                {type: "cancel", value: "Annuler"}
                            ],
                            afterShow: function() {
                                $('#mdp').focus()
                            },
                            success: function(result) {
                                if (result == "Valider") {
                                    if ($('#mdp').val() != '') {
                                        $.ajax({
                                            url: "{{ path('gds_devis_remise_depasse') }}",
                                            data: 'pass_remise=' + $('#mdp').val(),
                                            success: function(data) {
                                                if (data != 'failed') {
                                                    $('#gds_ventebundle_devistype_lignesDevis_' + i + '_taux_remise').spinner({
                                                        min: 0,
                                                        max: 100,
                                                        step: 1,
                                                        places: 2,
                                                        showOn: 'both'
                                                    });
                                                    article.remise_max = 100
                                                    article.prix_vente_min_ttc = 0
                                                }
                                            }
                                        })
                                    }
                                }
                            }
                        });
                    })
                    refraichir()
                }
                function Test(obj) {
                    var data = obj.value;
                    var d = data.substring(0, data.length - 1)
                    var index_virgule = data.indexOf('.')
                    if (index_virgule > 0)
                        apres_virgule = data.substring(data.indexOf('.') + 1, data.length)
                    if (!TestVerif(data) || apres_virgule.length > 3)
                        obj.value = d
                }
                function TestVerif(decimal) {
                    var entier = "0123456789"
                    var virgule = false
                    var first_number = false
                    var count_decimal = decimal.length
                    for (var index_verif = 0; index_verif < count_decimal; index_verif++) {
                        if (entier.indexOf(decimal[index_verif]) < 0) {
                            if (decimal[index_verif] == '.' && first_number) {
                                if (virgule)
                                    return false
                                else
                                    virgule = true
                            } else {
                                return false
                            }
                        } else {
                            first_number = true
                        }
                    }
                    return true
                }
                function chercherSousFamilles() {
                    $('#td_sous_familles ul').remove()
                    $.ajax({
                        url: '{{path('gds_vente_get_sous_familles_where_familles')}}',
                        datatype: 'json',
                        data: 'familles={"familles":' + JSON.stringify(familles) + '}',
                        success: function(data) {
                            $('#sous_familles').tokenInput(data, {
                                preventDuplicates: true,
                                onAdd: function(item) {
                                    sous_familles[sous_familles.length] = item.id
                                    chercherArticles('sous')
                                },
                                onDelete: function(item) {
                                    sous_familles.splice($.inArray(item.id, sous_familles), 1);
                                    chercherArticles('sous')
                                },
                            });
                        }
                    })
                }
                function chercherArticles(from) {
                    if (from == 'famille')
                        sous_familles = []
                    $('#td_articles ul').remove()
                    $.ajax({
                        url: '{{path('gds_vente_get_articles_where_familles')}}',
                        data: 'familles={"familles":' + JSON.stringify(familles) + ',"sous_familles":' + JSON.stringify(sous_familles) + '}&client_id=' + client_id,
                        datatype: 'json',
                        success: function(data) {
                            $("#articles").tokenInput(data, {
                                preventDuplicates: true,
                                onAdd: function(item) {
                                    $('#td_articles').children('.token-input-list').children('.token-input-token').hide()
                                    var article = getArticle(item.id)
                                    if (!article) {
                                        add_ligne()
                                        var article = item.name.split(' : ');
                                        var reference = article[0]
                                        var designation = article[1]
                                        articles.push(item)
                                        var id = index - 1
                                        $('#td_reference_' + id).html(reference)
                                        $('#td_designation_' + id).html(designation)
                                        $('#gds_ventebundle_devistype_lignesDevis_' + id + '_article').val(item.id)
                                        remplir_ligne(id, item)
                                        setQuantite(id)
                                        var remise_max = item.remise_max;
                                        $('#gds_ventebundle_devistype_lignesDevis_' + id + '_taux_remise').spinner({
                                            min: 0,
                                            max: remise_max,
                                            step: 1,
                                            places: 2,
                                            showOn: 'both'
                                        });
                                    } else {
                                        id = article.index
                                    }
                                    $('#gds_ventebundle_devistype_lignesDevis_' + id + '_quantite').focus()
                                },
                            });
                            $('#token-input-articles').focus()
                        }
                    })
                }
                function remplir_ligne(id, item) {
                    $('#gds_ventebundle_devistype_lignesDevis_' + id + '_prix_unitaire_ht').val(item.prix_vente)
                    $('#gds_ventebundle_devistype_lignesDevis_' + id + '_taux_remise').val(item.remise)
                    $('#td_tva_' + id).html(item.taux_tva + '%')
                }
                function delete_ligne(index) {
                    var article = getArticle($('#gds_ventebundle_devistype_lignesDevis_' + index + '_article').val())
                    var cmp_delete = 0
                    var article_deleted = false
                    while (!article_deleted && cmp_delete < articles.length) {
                        if (articles[cmp_delete] == article) {
                            articles.splice(cmp_delete, 1)
                            article_deleted = true
                        }
                        cmp_delete++
                    }
                    $('#tr_' + index).remove();
                    $('.token-input-list li').each(function() {
                        var name = article.name
                        if ($(this).children("p").html() == name)
                            $(this).remove()
                    })
                    refraichir()
                    RefraichirTaxe()
                }
                function refraichir() {
                    i = 1
                    $('.numero_ligne').each(function() {
                        $(this).html(i)
                        i++
                    })
                }
                function getArticle(id) {
                    var count_articles = articles.length
                    for (var i = 0; i < count_articles; i++) {
                        if (articles[i].id == id) {
                            return articles[i]
                        }
                    }
                    return null
                }
                function inverser(tab, i, j, tab2) {
                    var temp = tab[i];
                    var base = tab2[i]['base']
                    var montant = tab2[i]['montant']
                    var tva = tab2[i]['tva']
                    tab[i] = tab[j];
                    tab[j] = temp;
                    tab2[i]['base'] = tab2[j]['base']
                    tab2[j]['base'] = base
                    tab2[i]['montant'] = tab2[j]['montant']
                    tab2[j]['montant'] = montant
                    tab2[i]['tva'] = tab2[j]['tva']
                    tab2[j]['tva'] = tva
                }
                function TriTab(tab, tab2) {
                    var n = tab.length;
                    var continuer = true;
                    var i = 0;
                    var iter = 0;
                    while (continuer) {
                        iter++;
                        continuer = false;
                        for (i = 0; i < n - 1; i++) {
                            if (Math.max(tab[i], tab[i + 1]) != tab[i + 1]) {
                                inverser(tab, i, i + 1, tab2);
                                continuer = true;
                            }
                        }
                    }
                    return tab2;
                }
                function changerClient() {
                    chercherArticles()
                    if (articles.length != 0) {
            changerRemiseClient()
                    }
                }
                function changerRemiseClient() {
                    $.msgBox({
                        title: "Chargement Remise",
                        content: "Voulez-vous charger les remises du nouveau client ?",
                        type: "confirm",
                        buttons: [{value: "OUI"}, {value: "NON"}, {value: "Annuler"}],
                        success: function(result) {
                            if (result == "OUI") {
                                changeRemiseClient()
                            }
                        }
                    });
                }
                function changeRemiseClient() {
                    articles_to_modify = new Array()
                    index_modify = new Array()
                    $('#gds_ventebundle_lignedevistype tr').each(function() {
                        var ii = $(this).attr('id');
                        ii = ii.split('_');
                        ii = ii[1]
                        if ($('#designation_' + ii).val() != "") {
                            articles_to_modify[articles_to_modify.length] = $('#gds_ventebundle_devistype_lignesDevis_' + ii + '_article').val()
                            index_modify[index_modify.length] = ii
                        }
                    })
                    $.ajax({
                        url: '{{path("gds_vente_get_remises_client")}}',
                        type: "POST",
                        data: {'articles': articles_to_modify, 'client_id': client_id},
                        dataType: 'json',
                        success: function(data) {
                            var count_index_modify = index_modify.length
                            for (i = 0; i < count_index_modify; i++) {
                                if (data[i] != null) {
                                    $('#gds_ventebundle_devistype_lignesDevis_' + index_modify[i] + '_taux_remise').val(data[i])
                                    doRemiseChange(index_modify[i])
                                }
                            }
                            RefraichirTaxe()
                        }
                    })

                }

                function setQuantite(id) {
                    $.ajax({
                        url: "{{ path('gds_devis_qte_disponible') }}",
                        data: 'reference=' + $('#td_reference_' + id).html() + '&departement=' + $('#departement option:selected').text(),
                        success: function(data) {
                            if (data == 'failed')
                                $('#td_qte_dispo_' + id).html('')
                            else {
                                var qte_all = data['qte_all'] + data['qte_all_2']
                                if ($('#departement option:selected').val() == 0) {
                                    $('#td_qte_dispo_' + id).html(qte_all)
                                } else {
                                    var qte_dep = data['qte'] + data['qte_2']
                                    $('#td_qte_dispo_' + id).html("<span class='green'><b>" + qte_dep + "</b></span><span class='red'><b>|</b></span>" + qte_all)
                                }
                            }
                        }
                    })
                }
                function RefraichirTaxe() {
                    var rowCount = $('#gds_ventebundle_lignedevistype tr').length
                    var total_ttc = 0
                    var total_remise = 0
                    var taux_tva = new Array();
                    var taxes = new Array();
                    for (i = 0; i < rowCount; i++) {
                        taxes[i] = new Array()
                        taxes[i]['tva'] = 0
                        taxes[i]['base'] = 0
                        taxes[i]['montant'] = 0
                    }
                    var cmp = 0
                    var i_refraich = 0
                    while (cmp < rowCount) {
                        if ($('#td_total_' + i_refraich).html() != null) {
                            var tva = parseFloat($('#td_tva_' + i_refraich).html())
                            if (parseFloat($('#td_total_' + i_refraich).html()) > 0) {
                                var j = $.inArray(tva, taux_tva)
                                if (j == -1) {
                                    taux_tva.push(tva)
                                    j = $.inArray(tva, taux_tva)
                                }
                                var prix_depart = $('#gds_ventebundle_devistype_lignesDevis_' + i_refraich + '_prix_unitaire_ht').val()
                                var prix_depart_avec_tva = prix_depart * (1 + tva / 100)
                                var quantite = $('#gds_ventebundle_devistype_lignesDevis_' + i_refraich + '_quantite').val()
                                var ttc = parseFloat($('#td_total_' + i_refraich).html())
                                var montant_remise = quantite * prix_depart_avec_tva - ttc
                                total_remise += montant_remise
                                total_ttc += ttc
                                var ht = ttc / (1 + tva / 100)
                                var montant = ht * tva / 100
                                taxes[j]['tva'] = tva
                                taxes[j]['base'] += ht
                                taxes[j]['montant'] += montant
                            }
                            cmp++
                        }
                        i_refraich++
                    }
                    taxes = TriTab(taux_tva, taxes)
                    $('#taxe_body tr').remove()
                    var totaux = 0
                    var count_taux_tva = taux_tva.length
                    for (var i = 0; i < count_taux_tva; i++) {
                        tva = taxes[i]['tva'].toFixed(2)
                        totaux += taxes[i]['montant']
                        $('#taxe_body').append('<tr id="tr_taxe_' + tva + '"><td id="taxe_' + tva + '">' + tva + '%</td><td id="base_' + tva + '">' + taxes[i]['base'].toFixed(3) + '</td><td id="montant_taxe_' + tva + '">' + taxes[i]['montant'].toFixed(3) + '</td></tr>');
                    }
                    $('#taxe_body').append('<tr><td>Totaux</td><td></td><td id="total_taxe">' + totaux.toFixed(3) + '</td></tr>');
                    $('#total_ttc').html(total_ttc.toFixed(3))
                    $('#total_remise').html(total_remise.toFixed(3))
                    if (key_success != '') {
                        key = key_success
                        keyEnterPressed2()
                    }
                }
                function doRemiseChange(i) {
                    var article = getArticle($('#gds_ventebundle_devistype_lignesDevis_' + i + '_article').val())
                    article.remise = $('#gds_ventebundle_devistype_lignesDevis_' + i + '_taux_remise').val()
                    var quantite = $('#gds_ventebundle_devistype_lignesDevis_' + i + '_quantite').val();
                    var prix_vente_ht = $('#gds_ventebundle_devistype_lignesDevis_' + i + '_prix_unitaire_ht').val();
                    var tva = article.taux_tva;
                    var puttc = prix_vente_ht
                    puttc *= (1 + tva / 100)
                    puttc *= (1 - article.remise / 100)
                    puttc = puttc.toFixed(3)
                    $('#prix_u_ttc_' + i).val(puttc);
                    var total = puttc * quantite
                    $('#td_total_' + i).html(total.toFixed(3));
                }
                function time() {
                    var time = new Date($.now())
                    var h = time.getHours() // 0-24 format
                    var m = time.getMinutes()
                    var s = time.getSeconds()
                    $('#heure').val(s + m * 60 + h * 3600)
                    if (h < 10)
                        h = '0' + h
                    if (m < 10)
                        m = '0' + m
                    if (s < 10)
                        s = '0' + s
                    $('#now').val(h + ':' + m + ':' + s)
                }


                function Imprimer(id) {
                    $.ajax({
                        url: '{{path('gds_devis_print_saved')}}',
                        type: "POST",
                        data: 'id=' + id,
                        success: function(data) {

                            $.msgBox({
                                title: "Devis",
                                content: "Enregistrement Effectué avec succés",
                                type: "info",
                                buttons: [{value: "OK"}],
                                success: function(result) {
                                    location.reload();
                                }
                            });
                        }
                    })
                }
                function keyEnterPressed2() {
                    key_success = key
                    key = key.substr(0, key.length - 1);
                    var lignes = remplirLignes()
                    $.ajax({
                        url: '{{path('gds_devis_benefice')}}',
                        type: "POST",
                        datatype: 'json',
                        mode: 'abort',
                        data: 'contenu={"lignes":' + JSON.stringify(lignes) + '}&key=' + key + '&departement=' + $("#departement option:selected").text() + '&facturable=' + $('#facturable').is(':checked'),
                        success: function(data) {
                            if (data != 'failed')
                            {
                                var benefice_total = 0
                                if (data['qte'] != '') {
                                    $('#th_dispo').css("width", "10%")
                                    var count_data = data['qte'].length
                                    for (var i_qte = 0; i_qte < count_data; i_qte++) {
                                        var index = lignes[i_qte].index
                                        var qte_all = data['qte'][i_qte]['qte_all']
                                        var qte_all_2 = data['qte'][i_qte]['qte_all_2']
                                        if ($('#departement option:selected').val() == 0) {
                                            $('#td_qte_dispo_' + index).html("<span class='green'>" + qte_all + "</span>" + "*" + qte_all_2 + "</span>")
                                        } else {
                                            var qte_dep = data['qte'][i_qte]['qte']
                                            var qte_dep_2 = data['qte'][i_qte]['qte_2']
                                            $('#td_qte_dispo_' + index).html("<b><span class='green'>" + qte_dep + "</span>" + "*" + qte_dep_2 + "</span>" + "</b><span class='red'><b>|</b></span>" + "<span class='green'>" + qte_all + "</span>" + "*" + qte_all_2 + "</span>")
                                        }
                                        var ben = data['benefice'][i_qte]
                                        var total = lignes[i_qte].total
                                        $('#td_total_' + index).html(total + ' | ' + ben.toFixed(3))
                                        benefice_total += ben
                                    }
                                } else {
                                    var count_data = data['benefice'].length
                                    for (i_qte = 0; i_qte < count_data; i_qte++) {
                                        var index = lignes[i_qte].index
                                        var ben = data['benefice'][i_qte]
                                        var total = lignes[i_qte].total
                                        $('#td_total_' + index).html(total + ' | ' + ben.toFixed(3))
                                        benefice_total += ben
                                    }
                                }
                                var total_ttc = $('#total_ttc').html()
                                total_ttc = total_ttc.split('|')
                                total_ttc = total_ttc[0]
                                $('#total_ttc').html(total_ttc + ' | ' + benefice_total.toFixed(3))
                            } else {
                                key_success = ''
                                $('#th_dispo').css("width", "5%")
                                setTousQuantite()
                                var count_lines = lignes.length
                                for (i_qte = 0; i_qte < count_lines; i_qte++) {
                                    var index = lignes[i_qte].index
                                    $('#td_total_' + index).html(lignes[i_qte].total)
                                }
                                var total_ttc = $('#total_ttc').html()
                                total_ttc = total_ttc.split('|')
                                total_ttc = total_ttc[0]
                                $('#total_ttc').html(total_ttc)
                            }
                        }
                    })
                    key = ''
                }
                function remplirLignes() {
                    var cmp = 0
                    var lignes = new Array()
                    $('#gds_ventebundle_lignedevistype tr').each(function() {
                        var i = $(this).attr('id');
                        i = i.split('_');
                        i = i[1]
                        var article = getArticle($('#gds_ventebundle_devistype_lignesDevis_' + i + '_article').val())
                        lignes[cmp] = article
                        lignes[cmp].index = i
                        var total = $('#td_total_' + i).html()
                        total = total.split('|')
                        total = total[0]
                        lignes[cmp].total = total
                        cmp++
                    })
                    return lignes
                }
                function remplirTaxes() {
                    var taxes = new Array()
                    $('#taxe_body tr').each(function() {
                        var taxe = new Object()
                        var cmp = 0
                        $(this).find('td').each(function() {
                            if (cmp == 0) {
                                taxe.taux_tva = $(this).html()
                                cmp++
                            } else if (cmp == 1) {
                                taxe.base = $(this).html()
                                cmp++
                            } else {
                                taxe.montant = $(this).html()
                            }
                        })
                        taxes[taxes.length] = taxe
                    })
                    return taxes
                }
                function remplirOthers() {
                    var others = new Object()
                    others.date = $('#gds_ventebundle_devistype_date').val()
                    others.heure = $('#now').val()
                    others.client = client_id
                    others.ttc = $('#total_ttc').html()
                    return others
                }
                function setTousQuantite() {
                    var references = new Array()
                    var iis = new Array()
                    var cmp = 0
                    $('#gds_ventebundle_lignedevistype tr').each(function() {
                        var ii = $(this).attr('id');
                        ii = ii.split('_');
                        ii = ii[1]
                        references[cmp] = $('#td_reference_' + ii).html()
                        iis[cmp] = ii
                        cmp++
                    })
                    $.ajax({
                        url: "{{ path('gds_devis_all_qte_disponible') }}",
                        data: 'references=' + JSON.stringify(references) + '&departement=' + $('#departement option:selected').text(),
                        success: function(data) {
                            var count_lines = iis.length
                            for (var i = 0; i < count_lines; i++) {
                                var qte_all = data[i]['qte_all'] + data[i]['qte_all_2']
                                if ($('#departement option:selected').val() == 0) {
                                    $('#td_qte_dispo_' + iis[i]).html(qte_all)
                                } else {
                                    var qte_dep = data[i]['qte'] + data[i]['qte_2']
                                    $('#td_qte_dispo_' + iis[i]).html("<span class='green'><b>" + qte_dep + "</b></span><span class='red'><b>|</b></span>" + qte_all)
                                }
                            }

                        }
                    })
                }
                </script>
                <style>
                        .red {
                            color: red;
                            font-size: 18px;
                        }
                        .green{
                            color : green;
                        }
                    </style>